from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from user.models import *
import re
import redis
from captcha.image import ImageCaptcha
import random, string
from django.http import HttpResponse
import jwt
from chuizi import settings


class CheckUsername(APIView):
    def get(self, request, username):
        if username == 'a':
            return Response({
                'code': 204,
                'msg': '用户名不能为空'
            })
        if not re.findall(r'^[a-zA-Z]\w{6,15}a$', username):
            return Response({
                'code': 204,
                'msg': '用户名不符合规则'
            })
        if User.objects.filter(username=username):
            return Response({
                'code': 204,
                'msg': '用户名重复'
            })
        else:
            return Response({
                'code': 200,
                'msg': '用户名可用'
            })


class CheckMobile(APIView):
    def get(self, request, mobile):
        if mobile == 'a':
            return Response({
                'code': 204,
                'msg': '手机号不能为空'
            })
        if not re.findall(r'^1[3-9]\d{9}a$', mobile):
            return Response({
                'code': 204,
                'msg': '手机号不符合规则'
            })
        if User.objects.filter(mobile=mobile):
            return Response({
                'code': 204,
                'msg': '手机号重复'
            })
        else:
            return Response({
                'code': 200,
                'msg': '手机号可用'
            })


class Image(APIView):
    def get(self, request, uuid):
        code = ''.join(random.sample(string.digits + string.ascii_letters, 4))
        img = ImageCaptcha()
        img_code = img.generate(code)
        res = redis.Redis(host='localhost', port=6379, db=3)
        res.set(str(uuid), code, ex=60)
        res.close()
        return HttpResponse(img_code, content_type='image/png')


class CheckImg(APIView):
    def post(self, request):
        uuid = request.data.get('uuid')
        checkimg = request.data.get('imgcode')
        res = redis.Redis(host='localhost', port=6379, db=3)
        res_code = res.get(uuid).decode()
        if not res_code:
            return Response({
                'code': 204,
                'msg': '验证码过期'
            })
        if str(checkimg).lower() == str(res_code).lower():
            return Response({
                'code': 200,
                'msg': 'OK'
            })
        return Response({
            'code': 204,
            'msg': '验证码错误'
        })


class Register(APIView):
    def post(self, request):
        username = request.data.get('user')
        pwd = request.data.get('pass')
        mobile = request.data.get('mobile')
        print(username, pwd, mobile)
        if not all([username, pwd, mobile]):
            return Response({
                'code': 204,
                'msg': '数据不完整'
            })
        User.objects.create_user(username=username, password=pwd, mobile=mobile)
        return Response({
            'code': 200,
            'msg': '注册成功'
        })


def gen_token(user):
    payload = {
        'user_id': user.id,
        'name': user.username,
        'mobile': user.mobile
    }
    token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
    return token


class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        pwd = request.data.get('pwd')
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            print(e)
            return Response({
                'code': 204,
                'msg': '用户不存在'
            })
        if not user.check_password(pwd):
            return Response({'code': 204, 'msg': '用户或密码错误'})
        token = gen_token(user)
        return Response({
            'code': 200,
            'msg': '用户%s登录成功' % user.username,
            'token': token,
            'user': {
                'username': username,
                'uid': user.id,
                'touxiang': 'http://127.0.0.1:8000/static/touxiang/aaaa.png'
            }
        })


